
package com.gitee.jmash.storage.dao;

import com.gitee.jmash.common.utils.UUIDUtil;
import com.gitee.jmash.core.orm.DtoPage;
import com.gitee.jmash.core.orm.DtoTotal;
import com.gitee.jmash.core.orm.jpa.BaseDao;
import com.gitee.jmash.core.orm.jpa.SqlBuilder;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.storage.entity.StorageOrganInfoEntity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jmash.storage.protobuf.StorageOrganInfoReq;
import org.apache.commons.lang3.StringUtils;

/**
 * StorageOrganInfo实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class StorageOrganInfoDao extends BaseDao<StorageOrganInfoEntity, UUID> {

  public StorageOrganInfoDao() {
    super();
  }

  public StorageOrganInfoDao(TenantEntityManager tem) {
    super(tem);
  }

  /**
   * 查询服务组织.
   */
  public StorageOrganInfoEntity findOrganService(UUID organId, String serviceType) {
    String sql =
        "select s from StorageOrganInfoEntity s   where s.organId = ?1 and s.serviceType=?2 ";
    return this.findSingle(sql, organId, serviceType);
  }

  /**
   * 查询记录数.
   */
  public Integer findCount(StorageOrganInfoReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select count(s) ");
    Object obj = this.findSingleResultByParams(query, sqlBuilder.getParams());
    return (obj == null) ? 0 : Integer.valueOf(obj.toString());
  }

  /**
   * 综合查询.
   */
  public List<StorageOrganInfoEntity> findListByReq(StorageOrganInfoReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    return this.findListByParams(query, sqlBuilder.getParams());
  }

  /**
   * 综合查询Page.
   */
  public DtoPage<StorageOrganInfoEntity, DtoTotal> findPageByReq(StorageOrganInfoReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    String totalQuery = sqlBuilder.getTotalSql("select count(s) as totalSize ");
    return this.findDtoPageByParams(req.getCurPage(), req.getPageSize(), query, totalQuery,
        DtoTotal.class, sqlBuilder.getParams());
  }

  /** Create SQL By Req . */
  public SqlBuilder createSql(StorageOrganInfoReq req) {
    StringBuilder sql = new StringBuilder(" from StorageOrganInfoEntity s where 1=1  ");
    Map<String, Object> params = new HashMap<String, Object>();

    if (StringUtils.isNotBlank(req.getOrganId())) {
      sql.append("and s.organId =:organId ");
      params.put("organId", UUIDUtil.fromString(req.getOrganId()));
    }
    if (req.getHasStatus()) {
      sql.append("and s.status =:status ");
      params.put("status", req.getStatus());
    }
    if (StringUtils.isNotBlank(req.getUnifiedId())) {
      sql.append("and EXISTS (select 1 from StorageOrganUserEntity t where s.organId = t.organId and t.unifiedId=:unifiedId) ");
      params.put("unifiedId", req.getUnifiedId());
    }

    if (!req.getServiceTypeList().isEmpty()) {
      sql.append("and s.serviceType in :serviceTypes ");
      params.put("serviceTypes", req.getServiceTypeList());
    }

    if (StringUtils.isNotBlank(req.getLikeOrganName())){
      sql.append("and s.organName like :likeOrganName ");
      params.put("likeOrganName", "%" + req.getLikeOrganName() + "%");
    }

    String orderSql = " order by s.createTime desc ";
    if (StringUtils.isNotBlank(req.getOrderName())) {
      orderSql = String.format(" order by %s %s ", req.getOrderName(),
          req.getOrderAsc() ? " asc " : " desc ");
    }

    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

  /** 我的组织列表. */
  public List<StorageOrganInfoEntity> findMyStorageOrganList(List<String> serviceTypes,
                                                             String unifiedId) {
    SqlBuilder sqlBuilder = createMyOrganSql(serviceTypes, unifiedId);
    return this.findListByParams(sqlBuilder.getQuerySql(""), sqlBuilder.getParams());
  }

  /** 我的默认组织. */
  public StorageOrganInfoEntity findMyDefaultStorageOrgan(List<String> serviceTypes,
                                                          String unifiedId) {
    SqlBuilder sqlBuilder = createMyOrganSql(serviceTypes, unifiedId);
    List<StorageOrganInfoEntity> list =
        this.findListByParams(0, 1, sqlBuilder.getQuerySql(""), sqlBuilder.getParams());
    return list.isEmpty() ? null : list.get(0);
  }

  /** 我的浏览组织列表. */
  public List<StorageOrganInfoEntity> findMyStorageOrganBrowseList(List<String> serviceTypes,
      String unifiedId) {
    SqlBuilder sqlBuilder = createBrowseOrganSql(serviceTypes, unifiedId);
    return this.findListByParams(sqlBuilder.getQuerySql(""), sqlBuilder.getParams());
  }

  /** Create SQL By Req . */
  public SqlBuilder createMyOrganSql(List<String> serviceTypes, String unifiedId) {
    StringBuilder sql = new StringBuilder(
        "select s from StorageOrganInfoEntity s ,StorageOrganUserEntity t  where s.organId = t.organId ");
    sql.append("and s.status = true  and t.unifiedId = :unifiedId ");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("unifiedId", unifiedId);
    if (!serviceTypes.isEmpty()) {
      sql.append("and s.serviceType in :serviceTypes ");
      params.put("serviceTypes", serviceTypes);
    }
    String orderSql = " order by t.orderBy asc ";
    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

  /** 浏览语句构建 . */
  public SqlBuilder createBrowseOrganSql(List<String> serviceTypes, String unifiedId) {
    StringBuilder sql = new StringBuilder(
        "select s from StorageOrganInfoEntity s ,StorageOrganBrowserEntity t  where s.organId = t.organId and s.serviceType = t.serviceType ");
    sql.append("and s.status = true  and t.unifiedId = :unifiedId ");
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("unifiedId", unifiedId);
    if (!serviceTypes.isEmpty()) {
      sql.append("and t.serviceType in :serviceTypes ");
      params.put("serviceTypes", serviceTypes);
    }
    String orderSql = " order by t.lastBrowseTime desc ";
    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

  /**
   * 删除组织.
   */
  public int deleteByIdAndType(String organId, String serviceType) {
    String sql =
        "delete from StorageOrganInfoEntity s where s.organId = ?1 and s.serviceType = ?2";
    return this.executeUpdate(sql, UUIDUtil.fromString(organId), serviceType);
  }
}
